package com.yrxy.thread.interview.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className com.yrxy.thread.interview.cas.ABADemo2
 * @description：
 * @date 2017/5/21 21:07
 */
public class ABADemo2 {
    private static AtomicStampedReference<Integer> value =
            new AtomicStampedReference<>(1, 0);
    public static void main(String[] args){
        Thread thread1 = new Thread(() -> {
            System.out.println("线程名称: " + Thread.currentThread().getName() +",初始值 = " + value.getReference());
            int stamp = value.getStamp();
            try {
                Thread.sleep(2000); //等待2秒 ，以便让干扰线程执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("11 value is:"+value);
            boolean isCASSuccess = value.compareAndSet(1,2,stamp,stamp +1);  //此时expectedReference未发生改变，但是stamp已经被修改了,所以CAS失败
            System.out.println("22 value is:"+value);
            System.out.println("线程名称: " +  Thread.currentThread().getName() +",CAS操作结果: " + isCASSuccess);
        },"主操作线程");
        Thread thread2 = new Thread(() -> {
            Thread.yield(); // 确保thread1 优先执行
            value.compareAndSet(1,2, value.getStamp(), value.getStamp() +1);
            System.out.println("线程名称: " +  Thread.currentThread().getName() +",执行加操作 ,值 = "+ value.getReference());
            value.compareAndSet(2,1, value.getStamp(), value.getStamp() +1);
            System.out.println("线程名称: " +  Thread.currentThread().getName()+",执行减操作  ,值 = "+ value.getReference());
        },"干扰线程");
        thread1.start();
        thread2.start();
    }

}
